package example.org;

import java.io.File;
import java.io.FileOutputStream;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class ScreenshotActivity extends Activity {
	// private Panel mPanel;
	private String screenShotPath = Environment.getExternalStorageDirectory()
			+ "/ScreenShooter/";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		// mPanel = new Panel(this);
		// setContentView(mPanel);

		File directory = new File(screenShotPath);
		if (directory.exists()) {
			Toast.makeText(this, "Directory Exists", Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(this, "Directory Don't Exists", Toast.LENGTH_LONG)
					.show();

			if (directory.mkdir()) {
				Toast.makeText(this, "Directory Created", Toast.LENGTH_LONG)
				.show();
			}else{
				Toast.makeText(this, "Failed Create Directory", Toast.LENGTH_LONG)
				.show();
			}
		}

		setContentView(R.layout.main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.screenshot:
			// mPanel.saveScreenshot();
			View v = this.findViewById(android.R.id.content).getRootView();

			if (v != null) {
				v.setDrawingCacheEnabled(true);
				// this is the important code :)
				// Without it the view will have a dimension of 0,0 and the
				// bitmap
				// will be null
				// v.measure(
				// MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
				// MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
				v.layout(0, 0, v.getWidth(), v.getHeight());

				v.buildDrawingCache(true);
				Bitmap bitmap = v.getDrawingCache();
				String path = this.screenShotPath + "/"
						+ System.currentTimeMillis() + ".png";
				File file = new File(path);
				try {
					file.createNewFile();
					FileOutputStream ostream = new FileOutputStream(file);
					bitmap.compress(CompressFormat.PNG, 100, ostream);
					ostream.close();
					Toast.makeText(this, "Screen Capture", Toast.LENGTH_LONG)
							.show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				Toast.makeText(this, "Gagal", Toast.LENGTH_LONG).show();
			}
			break;
		}
		return true;
	}
}